# -*- coding: utf-8 -*-
from google.appengine.ext import db
from django.contrib.auth.models import User
from django.forms import ModelForm
from django import forms
from random import randint

class Joke(db.Model):
    content = db.StringProperty(required=True, multiline=True)
    active = db.BooleanProperty(required=True, default=True)
    created = db.DateTimeProperty(auto_now=False, auto_now_add=True)
    sender = db.ReferenceProperty(User, required=False, collection_name='joke_set')
    visited = db.IntegerProperty(required=False, default=0)
    
    @classmethod
    def create(cls, content, sender):
        joke = cls(content=content, sender=sender)
        joke.put()
        return joke
        
    @classmethod
    def get_by_random(cls):
        count = cls.all().count()
        if count == 0:
            return []
        offset = randint(0, count-1)
        query = cls.all()
        joke = query.filter('active =', True).fetch(1, offset)
        joke = joke[0]
        joke.visited = joke.visited + 1
        joke.put()
        return joke
    
class JokeForm(ModelForm):
    class Meta:
        model = Joke
        fields = ('content', )
        
    def clean_content(self):
        content = self.cleaned_data.get('content', '')
        num_words = len(content)
        if num_words < 6:
            raise forms.ValidationError("At least 6 words!")
        return content
